package algebra.visitors.cursors;

import entities.assertion.ConceptAssertion;
import algebra.op.AlgebraicOP;
import algebra.op.ProjectionOP;
import algebra.visitors.ProjectionOPEvaluator;

public class CACursorProjection extends CACursor {
	private CACursor subcursor;
	private final ProjectionOP op;
	private ConceptAssertion subres;

	public CACursorProjection(ProjectionOP op) {
		this.op = op;
		this.subcursor = null;
	}

	@Override
	public boolean openCursor() {
		// create a new cursor for subresults
		AlgebraicOP subop = this.op.getSubquery();
		this.subcursor = CACursor.getNewCACursor(subop);
		this.subcursor.openCursor();
		return true;
	}

	@Override
	public ConceptAssertion getNextResult() {
		this.subres = this.subcursor.getNextResult();
		ConceptAssertion ret = null;
		if (subres != null) {
			ProjectionOPEvaluator eval = new ProjectionOPEvaluator(
					op.getPlanEvalKB());
			ret = eval.visitPipelined(op, subres);
			if (ret == null) {
				return getNextResult();
			} else {
				return ret;
			}
		}
		return null;
	}

	@Override
	public boolean isSortedById() {
		return this.subcursor.isSortedById();
	}

}
